package com.ruoyi.functiontest.controller;

import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.functiontest.domain.InterchangeStatTest;
import com.ruoyi.functiontest.service.IInterchangeStatTestService;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 枢纽互通统计测试Controller
 * 
 * @author ruoyi
 * @date 2025-09-25
 */
@RestController
@RequestMapping("/functiontest/InterchangeStatTest")
public class InterchangeStatTestController extends BaseController
{
    @Autowired
    private IInterchangeStatTestService interchangeStatTestService;

    /**
     * 查询枢纽互通统计测试列表
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:list')")
    @GetMapping("/list")
    public AjaxResult list(InterchangeStatTest interchangeStatTest)
    {
        List<InterchangeStatTest> list = interchangeStatTestService.selectInterchangeStatTestList(interchangeStatTest);
        
        // 判断是否有搜索条件，如果有则构建树形结构返回
        boolean hasSearchCondition = interchangeStatTest.getRoadName() != null && !interchangeStatTest.getRoadName().isEmpty() ||
                                   interchangeStatTest.getNodeName() != null && !interchangeStatTest.getNodeName().isEmpty();
        
        if (hasSearchCondition) {
            // 有搜索条件时，构建树形结构返回，包含匹配节点及其所有子节点
            List<InterchangeStatTest> treeList = buildTree(list);
            return success(treeList);
        } else {
            // 无搜索条件时，返回扁平列表
            return success(list);
        }
    }

    /**
     * 导出枢纽互通统计测试列表
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:export')")
    @Log(title = "枢纽互通统计测试", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, InterchangeStatTest interchangeStatTest)
    {
        List<InterchangeStatTest> list = interchangeStatTestService.selectInterchangeStatTestList(interchangeStatTest);
        // 构建树形结构
        List<InterchangeStatTest> treeList = buildTree(list);
        // 只导出第二层的数据，并将第一层的路段名称存入第二层的路段名称中
        List<InterchangeStatTest> exportList = new ArrayList<>();
        for (InterchangeStatTest parent : treeList) {
            if (parent.getChildren() != null && !parent.getChildren().isEmpty()) {
                @SuppressWarnings("unchecked")
                List<InterchangeStatTest> children = (List<InterchangeStatTest>) parent.getChildren();
                for (InterchangeStatTest child : children) {
                    // 创建新的对象避免修改原数据
                    InterchangeStatTest exportItem = new InterchangeStatTest();
                    // 复制子节点的所有属性
                    exportItem.setId(child.getId());
                    exportItem.setParentId(child.getParentId());
                    exportItem.setNodeName(child.getNodeName());
                    exportItem.setMainLength(child.getMainLength());
                    exportItem.setRampAvgLength(child.getRampAvgLength());
                    exportItem.setTollCenterLength(child.getTollCenterLength());
                    exportItem.setApproachAvgLength(child.getApproachAvgLength());
                    exportItem.setRemark(child.getRemark());
                    // 将第一层的路段名称存入第二层的路段名称中
                    exportItem.setRoadName(parent.getRoadName());
                    exportList.add(exportItem);
                }
            }
        }
        ExcelUtil<InterchangeStatTest> util = new ExcelUtil<InterchangeStatTest>(InterchangeStatTest.class);
        util.exportExcel(response, exportList, "枢纽互通统计测试数据");
    }

    /**
     * 构建树形结构
     */
    private List<InterchangeStatTest> buildTree(List<InterchangeStatTest> list) {
        // 构建父子关系映射
        Map<Long, InterchangeStatTest> nodeMap = new HashMap<>();
        List<InterchangeStatTest> rootNodes = new ArrayList<>();
        
        // 先将所有节点放入map中
        for (InterchangeStatTest node : list) {
            nodeMap.put(node.getId(), node);
        }
        
        // 构建父子关系
        for (InterchangeStatTest node : list) {
            Long parentId = node.getParentId();
            if (parentId != null && parentId != 0) {
                InterchangeStatTest parent = nodeMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<InterchangeStatTest>());
                    }
                    @SuppressWarnings("unchecked")
                    List<InterchangeStatTest> children = (List<InterchangeStatTest>) parent.getChildren();
                    children.add(node);
                }
            } else {
                rootNodes.add(node);
            }
        }
        
        return rootNodes;
    }

    /**
     * 获取枢纽互通统计测试详细信息
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(interchangeStatTestService.selectInterchangeStatTestById(id));
    }

    /**
     * 新增枢纽互通统计测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:add')")
    @Log(title = "枢纽互通统计测试", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody InterchangeStatTest interchangeStatTest)
    {
        return toAjax(interchangeStatTestService.insertInterchangeStatTest(interchangeStatTest));
    }

    /**
     * 修改枢纽互通统计测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:edit')")
    @Log(title = "枢纽互通统计测试", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody InterchangeStatTest interchangeStatTest)
    {
        return toAjax(interchangeStatTestService.updateInterchangeStatTest(interchangeStatTest));
    }

    /**
     * 删除互通立交统计
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:remove')")
    @Log(title = "互通立交统计", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        for (Long id : ids) {
            if (interchangeStatTestService.hasChildById(id)) {
                return AjaxResult.error("节点存在子节点，请先删除子节点后再删除父节点");
            }
        }
        return toAjax(interchangeStatTestService.deleteInterchangeStatTestByIds(ids));
    }

    /**
     * 导入互通枢纽统计测试数据
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:import')")
    @Log(title = "互通枢纽统计测试", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<InterchangeStatTest> util = new ExcelUtil<InterchangeStatTest>(InterchangeStatTest.class);
        List<InterchangeStatTest> importList = util.importExcel(file.getInputStream());
        
        // 将扁平数据转换为树形结构并保存
        String message = interchangeStatTestService.importInterchangeStatTest(importList, updateSupport);
        return success(message);
    }

    /**
     * 导入模板下载
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:import')")
    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        List<InterchangeStatTest> templateList = new ArrayList<>();
        
        InterchangeStatTest example1 = new InterchangeStatTest();
        example1.setId(1L);
        example1.setRoadName("G1京哈高速");
        example1.setNodeName("北京互通");
        example1.setMainLength(new BigDecimal("1200.50"));
        example1.setRampAvgLength(new BigDecimal("800.25"));
        example1.setTollCenterLength(new BigDecimal("150.75"));
        example1.setApproachAvgLength(new BigDecimal("300.60"));
        example1.setRemark("示例数据1");
        templateList.add(example1);
        
        InterchangeStatTest example2 = new InterchangeStatTest();
        example2.setId(2L);
        example2.setRoadName("G1京哈高速");
        example2.setNodeName("沈阳枢纽");
        example2.setMainLength(new BigDecimal("1500.80"));
        example2.setRampAvgLength(new BigDecimal("950.40"));
        example2.setTollCenterLength(new BigDecimal("180.90"));
        example2.setApproachAvgLength(new BigDecimal("350.20"));
        example2.setRemark("示例数据2");
        templateList.add(example2);
        
        InterchangeStatTest example3 = new InterchangeStatTest();
        example3.setId(3L);
        example3.setRoadName("G2京沪高速");
        example3.setNodeName("天津互通");
        example3.setMainLength(new BigDecimal("1100.30"));
        example3.setRampAvgLength(new BigDecimal("700.15"));
        example3.setTollCenterLength(new BigDecimal("140.60"));
        example3.setApproachAvgLength(new BigDecimal("280.45"));
        example3.setRemark("示例数据3");
        templateList.add(example3);
        
        InterchangeStatTest example4 = new InterchangeStatTest();
        example4.setId(4L);
        example4.setRoadName("G2京沪高速");
        example4.setNodeName("上海枢纽");
        example4.setMainLength(new BigDecimal("1800.90"));
        example4.setRampAvgLength(new BigDecimal("1200.75"));
        example4.setTollCenterLength(new BigDecimal("220.30"));
        example4.setApproachAvgLength(new BigDecimal("420.80"));
        example4.setRemark("示例数据4");
        templateList.add(example4);
        
        ExcelUtil<InterchangeStatTest> util = new ExcelUtil<InterchangeStatTest>(InterchangeStatTest.class);
        util.exportExcel(response, templateList, "互通枢纽统计测试导入模板");
    }
    
    /**
     * 实测单位批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:fieldAudit')")
    @Log(title = "枢纽互通统计测试", businessType = BusinessType.UPDATE)
    @PostMapping("/fieldAudit/batch")
    public AjaxResult fieldAuditBatch()
    {
        try {
            // 批量更新所有记录的review1字段为0
            int updatedCount = interchangeStatTestService.updateReview1ToZero();
            System.out.println("实测单位批量审核完成，更新记录数：" + updatedCount);
            return success("实测单位批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("实测单位批量审核失败：" + e.getMessage());
            return error("实测单位批量审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 业主批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:ownerAudit')")
    @Log(title = "枢纽互通统计测试", businessType = BusinessType.UPDATE)
    @PostMapping("/ownerAudit/batch")
    public AjaxResult ownerAuditBatch(@RequestBody Map<String, Object> params)
    {
        try {
            Long deptId = params.get("deptId") != null ? Long.valueOf(params.get("deptId").toString()) : null;
            Long roleId = params.get("roleId") != null ? Long.valueOf(params.get("roleId").toString()) : null;
            
            System.out.println("业主批量审核 - 审核所有数据，deptId: " + deptId + ", roleId: " + roleId);
            
            // 1. 校验所有数据的review1字段是否都为0
            boolean allReview1Zero = interchangeStatTestService.checkAllReview1IsZero();
            if (!allReview1Zero) {
                return error("业主批量审核失败：存在未通过实测单位审核的数据，请先完成实测单位审核");
            }
            
            // 2. 构建查询条件
            InterchangeStatTest queryCondition = new InterchangeStatTest();
            queryCondition.setDeptId(deptId);
            queryCondition.setRoleId(roleId);
            
            // 3. 从params中提取查询条件
            if (params.get("roadName") != null) {
                queryCondition.setRoadName(params.get("roadName").toString());
            }
            if (params.get("nodeName") != null) {
                queryCondition.setNodeName(params.get("nodeName").toString());
            }
            
            // 4. 根据条件批量更新业主审核状态
            int updatedCount = interchangeStatTestService.updateReview2ToZeroByCondition(queryCondition);
            
            System.out.println("业主批量审核完成，更新记录数：" + updatedCount);
            return success("业主批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("业主批量审核失败：" + e.getMessage());
            return error("业主批量审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 中心批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:centerAudit')")
    @Log(title = "枢纽互通统计测试", businessType = BusinessType.UPDATE)
    @PostMapping("/centerAudit/batch")
    public AjaxResult centerAuditBatch()
    {
        try {
            System.out.println("中心批量审核 - 审核所有数据");
            
            // 1. 校验所有数据的review1和review2字段是否都不为空且都为0
            boolean allReview1AndReview2Zero = interchangeStatTestService.checkAllReview1AndReview2AreZero();
            if (!allReview1AndReview2Zero) {
                return error("中心批量审核失败：存在未通过实测单位审核或业主审核的数据，请先完成前序审核");
            }
            
            // 2. 批量更新中心审核状态
            int updatedCount = interchangeStatTestService.updateReview3ToZero();
            
            System.out.println("中心批量审核完成，更新记录数：" + updatedCount);
            return success("中心批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("中心批量审核失败：" + e.getMessage());
            return error("中心批量审核失败：" + e.getMessage());
        }
    }
}
